package com.zhipu.hydration.utils.serialport;


import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.zhipu.hydration.mobile.event.MessageEvent;
import com.zhipu.hydration.mobile.event.MessageType;
import com.zhipu.hydration.utils.InitializeUtils;

import org.greenrobot.eventbus.EventBus;

import android_serialport_api.SerialPortFinder;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;

/**
 * 按键串口
 */
public class KeySerialPortUtils {

    private static SerialPortFinder mSerialPortFinder;
    private static SerialHelper mSerialHelper;


    /**
     * 初始化按键串口
     */
    public static void InitializeKeySerialPort(){
        mSerialPortFinder = new SerialPortFinder();
        mSerialHelper = new SerialHelper("/dev/ttyS2", 9600) {
            @Override
            protected void onDataReceived(ComBean comBean) {
                if(null != comBean && null != comBean.bRec && comBean.bRec.length > 0){
                    int verify = (comBean.bRec[0] + comBean.bRec[1] + comBean.bRec[2] + comBean.bRec[3] + comBean.bRec[4]);
                    if(verify == 0){
                        System.out.println("校验成功");
                        EventBus.getDefault().post(new MessageEvent(MessageType.Keystroke).put(comBean.bRec[3]));
                    }else {
                        InitializeUtils.getDefaultMaker().show("校验失败");
                        LogUtils.d("校验失败" + GsonUtils.toJson(comBean.bRec));
                    }
//                    String mSwipeCard = CommonUtils.bytesToHex(comBean.bRec);
                    System.out.println("内容" + GsonUtils.toJson(comBean.bRec));
                }
            }
        };
        mSerialHelper.setDataBits(8);//数据位
        mSerialHelper.setParity(0);//校验位
        mSerialHelper.setStopBits(1);//停止位
        mSerialHelper.setFlowCon(0);//流控
        mSerialHelper.setiDelay(1000);
        try {
            mSerialHelper.open();//开启串口
            InitializeUtils.getDefaultMaker().show("开门串口" + mSerialHelper.getPort());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
